package cn.tedu.egarticle0811.controller;

import cn.tedu.egarticle0811.pojo.entity.Article;
import cn.tedu.egarticle0811.base.response.JsonResult;
import cn.tedu.egarticle0811.base.response.StatusCode;
import cn.tedu.egarticle0811.mapper.UserMapper;
import cn.tedu.egarticle0811.pojo.dto.UserArticleParam;
import cn.tedu.egarticle0811.pojo.dto.UserLoginParam;
import cn.tedu.egarticle0811.pojo.vo.ArticleVO;
import cn.tedu.egarticle0811.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.sql.rowset.JdbcRowSet;

@Slf4j
@Validated
@RestController
@RequestMapping("/v1/user/")
@Tag(name="用户模块",description = "用户管理接口")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("login")
    @Operation(summary = "用户登录",description = "用户登录接口")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("用户信息：" + userLoginParam);
        UserVO userVO = userMapper.selectUserByUsernameAndPassword(userLoginParam);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.ok(userVO);
    }

    @PostMapping("article")
    @Operation(summary = "发布文章")
    @ApiOperationSupport(order = 20)
    public JsonResult addArticle(@RequestBody @Validated UserArticleParam userArticleParam, HttpSession session){
        UserVO userVO = (UserVO)session.getAttribute("user");
        Article article = new Article();
        BeanUtils.copyProperties(userArticleParam,article);
        article.setUserId(userVO.getId());
        log.debug("发布文章，参数：{}",article);
        userMapper.insertArticle(article);
        return JsonResult.ok(article);
    }

    @GetMapping("selectByArticleId")
    @Operation(summary = "查询文章")
    @ApiOperationSupport(order = 30)
    public JsonResult selectByArticleId(@Range(min = 1l,max = 100l,message = "文章id范围错误") Long id ,HttpSession session){
        ArticleVO articleVO = userMapper.selectVyArticleId(id);
        return JsonResult.ok(articleVO);
    }
}
